package org.port.weather;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.port.R;
import org.port.util.Log;
import org.port.util.Util;
import org.port.weather.WeatherActivity.WeatherAction;
import org.port.weather.data.WeatherCP;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.widget.RemoteViews;

/**
 * @author WeeYeoungJong
 *	App쪽에서 BR을 날리면 Receive에서 받는다. 
 * 위젯을 등록할 때에는 onEnalbed가 활성화 됨.
 * 업데이트 시에는 onUpdate
 * 하지만 액션으로 미리 구분함.
 */
public class WeatherWidgetProvider extends AppWidgetProvider {
	private static final String TAG = "WeatherWidgetProvider";
	private RemoteViews rv;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onReceive: Action = " + intent.getAction());
		try {
			switch (WeatherAction.toAction(intent.getAction())) {
				case APPWIDGET_ENABLE :
					this.onEnabled(context);
					break;
				case APPWIDGET_UPDATE :
					AppWidgetManager manager = AppWidgetManager.getInstance(context);
					this.onUpdate(context, manager, manager.getAppWidgetIds(new ComponentName(context, WeatherWidgetProvider.class)));
					break;
				case UPDATE_WEATHER_TABLE :
					changeViewData(rv, context);
					break;

				default :
					super.onReceive(context, intent);
					break;
			}
		} catch (Exception e) {
			// TODO: handle exception
			super.onReceive(context, intent);
		}
	}

	@Override
	public void onEnabled(Context context) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onEnabled()");
		PackageManager pm = context.getPackageManager();
		pm.setComponentEnabledSetting(new ComponentName(context, WeatherWidgetProvider.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
				PackageManager.DONT_KILL_APP);
		rv = new RemoteViews(context.getPackageName(), R.layout.weather_widget_item);
		changeViewData(rv, context);
		super.onEnabled(context);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		Util.fileWrite(context, TAG + "-> " + new Date(System.currentTimeMillis()).toLocaleString() + ": onUpdate()");
		Log.d(TAG, "onUpdate()");
		final int N = appWidgetIds.length;
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];
			Intent intent = new Intent(context, WeatherActivity.class);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			if (rv == null) {
				rv = new RemoteViews(context.getPackageName(), R.layout.weather_widget_item);
			}
			changeViewData(rv, context);
			rv.setOnClickPendingIntent(R.id.weather_item2, pendingIntent);
			appWidgetManager.updateAppWidget(appWidgetId, rv);
		}
	}

	
	/*
	 * BR수신 시 위젯 상태 변경
	 */
	private void changeViewData(RemoteViews v, Context context) {
		Log.d(TAG, "changeViewData()");
		Date d = new Date(System.currentTimeMillis());
		String selection = WeatherCP.DATE + "= ? AND " + WeatherCP.STATE + " IS NOT NULL";
		String[] selectionArgs = {"0"};
		Cursor c = context.getContentResolver().query(WeatherCP.WEATHER_URI, null, selection, selectionArgs, WeatherCP.ID + " ASC");
		if (c != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM" + context.getString(R.string.str_month) + "dd" + context.getString(R.string.str_day), Locale.KOREA);

			Log.d(TAG, "" + sdf.format(new Date(System.currentTimeMillis())));
			if (c.moveToFirst()) {
				while (c.moveToNext()) {
					int h = Integer.parseInt(c.getString(c.getColumnIndexOrThrow(WeatherCP.HOUR)));
					if (h > d.getHours()) {
						Log.d(TAG, c.getPosition() + "");
						Log.d(TAG, "Hour: " + h + "  // Date.Hour: " + d.getHours());
						Log.d(TAG, c.getString(c.getColumnIndexOrThrow(WeatherCP.DATE)));
						v.setTextViewText(
								R.id.txt_date,
								sdf.format(new Date(System.currentTimeMillis())) + "  " + c.getString(c.getColumnIndexOrThrow(WeatherCP.HOUR))
										+ context.getString(R.string.str_hour));
						v.setImageViewResource(R.id.iv_state, Util.getStateImageId(c.getString(c.getColumnIndexOrThrow(WeatherCP.STATE))));
						v.setTextViewText(R.id.txt_temp, c.getString(c.getColumnIndexOrThrow(WeatherCP.TEMP)) + context.getString(R.string.str_temp));
						v.setTextViewText(R.id.txt_rain, c.getString(c.getColumnIndexOrThrow(WeatherCP.RAIN)) + context.getString(R.string.str_rain));
						c.close();
						break;
					}
				}
			}
		}
	}
}
